<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //retry 手写一个  失败后继续请求，可设置请求次数 决定是否缺点失败
        function fn() {
            const num = Math.ceil(Math.random() * 100); //生成1-100的随机数
            return new Promise((reslove, reject) => {
                setTimeout(() => {
                    if (num < 50) {
                        reslove(num)
                    } else {
                        reject(num)
                    }
                }, 1000)
            })
        }
        Promise.retry = (fn, times) => {
            new Promise(async (reslove, reject) => {
                while (times--) {
                    try {
                        const res = await fn()
                        console.warn('正确了', res)
                        times = 0
                        reslove(res)
                    } catch (error) {
                        console.warn('失败了', error)
                        if (!times) {
                            reject(error)
                        }
                    }
                }
            }).catch((error) => {
                console.warn('全部执行，失败')
                reject(error)
            })
        }
        Promise.retry(fn, 5)
    </script>
</body>

</html>